package com.ds.infrastructure.hyperspace.console.controller;

import com.ds.infrastructure.hyperspace.console.config.shiro.ShiroToken;
import com.ds.infrastructure.hyperspace.console.model.response.login.GetUserInfoVO;
import com.ds.infrastructure.hyperspace.console.model.response.result.JsonResultData;
import com.ds.infrastructure.hyperspace.console.service.impl.SSOService;
import com.ds.infrastructure.hyperspace.console.service.inf.ISSOService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;

import static com.ds.infrastructure.hyperspace.console.constants.ConsoleConstant.AUTHORIZATION_HEAD_KEY;

/**
 * 哗啦啦单点登录系统接入文档说明
 * http://wiki.ds.com/pages/viewpage.action?pageId=30243577&tdsourcetag=s_pctim_aiomsg
 *
 * @author: yaozhendong
 * @create: 2019-11-18 11:44
 **/
@Slf4j
@RestController
@RequestMapping(value = "/login", produces = {"application/json;charset=UTF-8"})
@Api(value = "Manager Login Controller", tags = "登录管理")
public class LoginController {
    @Autowired
    ISSOService iSSOService;

    @GetMapping(value = "/callback")
    @ApiOperation(value = "登录回调")
    public JsonResultData<GetUserInfoVO> callback(@RequestParam(name = "ticket") String ticket, HttpServletResponse response) {
        log.info(ticket);
        SSOService.UserId userId = iSSOService.validateTicket(ticket);
        SSOService.UserInfo userInfo = iSSOService.getUserInfo(userId.getSid());
        response.setHeader(AUTHORIZATION_HEAD_KEY, userId.getSid());
        response.setHeader("Access-Control-Expose-Headers", AUTHORIZATION_HEAD_KEY);
        GetUserInfoVO result = GetUserInfoVO.toVO(userInfo.getUsername(), userId.getSid());
        return JsonResultData.build(result);
    }

    @ApiIgnore
    @GetMapping(value = "/getUserInfo")
    @ApiOperation(value = "获取当前用户信息")
    public JsonResultData<GetUserInfoVO> getUserInfo() {
        ShiroToken.User currentUser = iSSOService.getCurrentUser();
        GetUserInfoVO result = GetUserInfoVO.toVO(currentUser.getName(), currentUser.getSid());
        return JsonResultData.build(result);
    }
}
